#!/bin/bash

readonly PROG_DIR=$(pwd)
readonly PID_FILE=$PROG_DIR/asch.pid

function read_port() {
  echo `cat $PROG_DIR/config.json |grep '"port"'|head -n 1| awk -F "[:,]" '{print$2}'|tr -d ' '`
}

function is_running() {
  test -f $PID_FILE && ps -p $(cat $PID_FILE) > /dev/null
}

function status() {
  if is_running; then
    echo "Asch server is running"
  else
    echo "Asch server is not running"
  fi
}

function start() {
  if is_running; then
    echo "Asch server is already started"
  else
    rm -f $PROG_DIR/asch.pid
    node $PROG_DIR/app.js --base $PROG_DIR --daemon $@
  fi
}

function stop() {
  local pid
  if test -f $PID_FILE; then
    pid=$(cat $PID_FILE)
  fi
  if [ -n "$pid" ] && ps -p "$pid" > /dev/null; then
    kill $pid
    sleep 1
    i=1
    while ps -p $pid > /dev/null; do
      if [ $i == 5 ]; then
        kill -9 $pid
        echo "Asch server killed"
      fi
      echo "Still waiting for asch server to stop ..."
      sleep 1
      ((i++))
    done
    echo "Asch server stopped"
  else
    echo "Asch server is not running"
  fi
  rm -f $PID_FILE
}

function restart() {
  stop
  start
}

function rebuild() {
  cd $PROG_DIR && curl -sL http://www.asch.so/downloads/rebuild-testnet.sh | bash
}

function version() {
  node $PROG_DIR/app.js --version
}

function check_os() {
	os_num=`cat /etc/os-release | grep '\"Ubuntu\"'  | wc -l`
	if [ $os_num -ne 1 ];then
		echo "Linux is not Ubuntu, please configure manually!" && exit 1
	fi
}

function configure() {
  check_os
  sudo $PROG_DIR/init/install_deps.sh
  sudo $PROG_DIR/init/config_ntp.sh
  sudo $PROG_DIR/init/config_monitor.sh
}

function upgrade() {
  cd $PROG_DIR && curl -sL http://www.asch.so/downloads/upgrade-testnet.sh | bash
}

function enable() {
  local secret="$@"
  local port=`read_port`
  curl -k -H "Content-Type: application/json" -X POST -d '{"secret":"'"$secret"'"}' localhost:$port/api/delegates/forging/enable
}

function main() {
  export PATH=$PROG_DIR/bin:$PATH
  local cmdType=`type -t $1`
  if [ $cmdType == "function" ]; then
    eval $@
  else
    echo "Command not supported"
  fi
}

main $@
